import { stores } from '@/stores/index.js'
//以函数的方式定义指令，会在mounted和updated中都执行
// const focus = (el, binding) => {
//     el.focus()
//     //el-input 适用
//    el.querySelector('.el-input__inner') && el.querySelector('.el-input__inner').focus()

// }

const focus = {
  mounted: (el) => {
    el.focus()
    el.querySelector('.el-input__inner') && el.querySelector('.el-input__inner').focus()
  }
}
//使用方法， 直接使用v-drag 或者带初始位置参数 v-drag=" { top:10,left:10} "
const drag = {
  mounted: (el, binding) => {
    const parentNode = el.parentNode
    // 获取父元素的定位属性
    const computedStyles = window.getComputedStyle(parentNode)
    // 如果父元素没有设置定位属性，则设置相对定位
    if (computedStyles.position === 'static') {
      parentNode.style.position = 'relative'
    }
    el.style.position = 'absolute'
    el.style.zIndex = 2000 //这里要设置成比element ui 弹框的z-index值低，否则会浮在弹框上层
    if (binding.value) {
      //传入了初始位置（left|top|right|bottom)
      for (const key in binding.value) {
        el.style[key] = parseInt(binding.value[key]) + 'px'
      }
    } else {
      el.style.top = 0
      el.style.left = 0
    }
    var disX = 0
    var disY = 0
    el.onmousedown = function (ev) {
      el.style.cursor = 'move'
      //鼠标事件对象
      disX = ev.clientX - el.offsetLeft
      disY = ev.clientY - el.offsetTop
      document.onmousemove = function (ev) {
        //鼠标事件对象
        var left = ev.clientX - disX
        var top = ev.clientY - disY
        if (left <= 0) {
          left = 0
        } else if (left > parentNode.clientWidth - el.offsetWidth) {
          left = parentNode.clientWidth - el.offsetWidth
        }
        if (top <= 0) {
          top = 0
        } else if (top > parentNode.clientHeight - el.offsetHeight) {
          top = parentNode.clientHeight - el.offsetHeight
        }
        el.style.left = left + 'px'
        el.style.top = top + 'px'
      }
      document.onmouseup = function () {
        // el.style.cursor = 'default'
        document.onmousemove = null
        document.onmouseup = null
      }

      //阻止默认事件
      return false
    }
    el.onmouseenter = function () {
      el.style.cursor = 'move'
    }
  }
}

//保持当前滚动位置
const keepScrolled = (el, binding) => {
  console.log('卷入的高度', el.scrollTop)
}
//根据登录人员的角色，控制是否显示某个元素 v-roles="['所领导岗位', '系统管理员岗位']"
const roles = (el, binding) => {
  // console.log('roles----', el)
  const userStore = stores.useUserStore()
  if (!binding.value.includes(userStore.userInfor.post)) {
    if (el.parentNode) {
      el.parentNode.removeChild(el)
    }
  }
}

export default {
  drag,
  focus,
  keepScrolled,
  roles
}
